package com.example.denglu;

import android.content.Intent; 
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    // 定义消息代码
    private static final int LOGIN_START = 1;
    private static final int LOGIN_FINISH = 2;
    private static final int LOGIN_SUCCESS = 3;
    private static final int LOGIN_FAILED = 4;

    private EditText editTextUsername;
    private EditText editTextPassword;
    private Button buttonLogin;
    private Button buttonRegister;
    private ProgressBar progressBar;
    private TextView textViewLoading;
    private View viewLoadingMask;
    private String currentUsername;

    private Thread loginThread;

    private final Handler handler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case LOGIN_START:
                    progressBar.setVisibility(View.VISIBLE);
                    textViewLoading.setVisibility(View.VISIBLE);
                    viewLoadingMask.setVisibility(View.VISIBLE);
                    buttonLogin.setEnabled(false);
                    buttonRegister.setEnabled(false);
                    break;
                case LOGIN_FINISH:
                    progressBar.setVisibility(View.GONE);
                    textViewLoading.setVisibility(View.GONE);
                    viewLoadingMask.setVisibility(View.GONE);
                    buttonLogin.setEnabled(true);
                    buttonRegister.setEnabled(true);
                    break;
                case LOGIN_SUCCESS:
                    Toast.makeText(MainActivity.this, "登录成功", Toast.LENGTH_SHORT).show();
                    Intent loginIntent = new Intent(MainActivity.this, HomeActivity.class);
                    loginIntent.putExtra("USERNAME", currentUsername);
                    startActivity(loginIntent);
                    finish();
                    break;
                case LOGIN_FAILED:
                    Toast.makeText(MainActivity.this, "用户名或密码错误", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_contest);
        initViews();
        setButtonListeners(); // 已绑定修正后的点击事件
    }

    private void initViews() {
        editTextUsername = findViewById(R.id.editText_username);
        editTextPassword = findViewById(R.id.editText_password);
        buttonLogin = findViewById(R.id.button_login);
        buttonRegister = findViewById(R.id.button_register);
        progressBar = findViewById(R.id.progressBar);
        textViewLoading = findViewById(R.id.textView_loading);
        viewLoadingMask = findViewById(R.id.view_loading_mask);
    }

    // 修正：注册按钮绑定handleRegister（不再复用登录逻辑）
    private void setButtonListeners() {
        buttonLogin.setOnClickListener(v -> handleLogin());
        // 原代码：buttonRegister.setOnClickListener(v -> handleLogin());
        buttonRegister.setOnClickListener(v -> handleRegister()); // 关键修改处
    }

    // 新增：注册按钮逻辑（暂留空实现，仅提示待开发，避免点击崩溃）
    private void handleRegister() {
        Toast.makeText(this, "注册功能待开发", Toast.LENGTH_SHORT).show();
    }

    // 登录逻辑（保持不变）
    private void handleLogin() {
        currentUsername = editTextUsername.getText().toString().trim();
        final String password = editTextPassword.getText().toString().trim();

        if (TextUtils.isEmpty(currentUsername)) {
            Toast.makeText(this, "请输入用户名", Toast.LENGTH_SHORT).show();
            return;
        }

        if (TextUtils.isEmpty(password)) {
            Toast.makeText(this, "请输入密码", Toast.LENGTH_SHORT).show();
            return;
        }

        loginThread = new Thread(() -> {
            handler.sendEmptyMessage(LOGIN_START);

            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                return;
            }

            handler.sendEmptyMessage(LOGIN_FINISH);

            if ("student".equals(currentUsername) && "666666".equals(password)) {
                handler.sendEmptyMessage(LOGIN_SUCCESS);
            } else {
                handler.sendEmptyMessage(LOGIN_FAILED);
            }
        });

        loginThread.start();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        handler.removeCallbacksAndMessages(null);
        if (loginThread != null && loginThread.isAlive()) {
            loginThread.interrupt();
        }
    }
}